/**
 * ===========================================
 * Project: gamehistory-web
 * ===========================================
 * Package: com.cyou.gamehistory.front.web
 * 
 * Copyright (c) 2012, CYOU All Rights Reserved.
 * ===========================================
 */
package com.cyou.gamehistory.front.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cyou.annals.util.AnnalsClient;
import com.cyou.framework.exception.ExceptionUtility;
import com.cyou.framework.mapper.JsonMapper;
import com.cyou.framework.util.DateUtility;
import com.cyou.gamehistory.entity.AppInfo;
import com.cyou.gamehistory.entity.GameHistoryFeed;
import com.cyou.gamehistory.entity.UserInfo;
import com.cyou.gamehistory.entity.vo.Account;
import com.cyou.gamehistory.entity.vo.MemberInfo;
import com.cyou.gamehistory.service.AppInfoService;
import com.cyou.gamehistory.service.GameHistoryFeedService;
import com.cyou.gamehistory.service.UserInfoService;
import com.cyou.gamehistory.util.ApplicationConfig;
import com.cyou.gamehistory.util.ApplicationConstants;
import com.cyou.gamehistory.util.WebUtil;

/**
 * <p>IndexController</p>
 *
 * @since 1.0
 * @version 1.0 2012-12-3
 * @author zhangxingkai
 */
@Controller
@RequestMapping(value = "/f")
public class IndexController {

	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

	@Autowired
	private AppInfoService appInfoService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private GameHistoryFeedService gameHistoryFeedService;
	
	private final JsonMapper jsonMapper = JsonMapper.nonDefaultMapper();
	
	private static String requestUrl = ApplicationConfig.getValue("requestUrl");

	@RequestMapping(value = { "", "index" })
	public String index(Model model, HttpSession session,HttpServletRequest request,HttpServletResponse response) {

		// 获取appInfo
		AppInfo appInfo = appInfoService.getAppInfo();
		model.addAttribute("appInfo", appInfo);
		
		// 获取8条最新动态，后续AJAX请求最新数据，每隔10秒发送一次请求
		List<GameHistoryFeed> feedList = gameHistoryFeedService.getLastestFeeds(8);
		model.addAttribute("feedList", feedList);

		// 获取游戏达人控，直接取排行前50名，开始翻页，不使用AJAX
		List<UserInfo> topUserList = userInfoService.getTopUserInfoList();
		model.addAttribute("topUserList", topUserList);
		model.addAttribute("size", topUserList.size());
		
		// 获取登录用户信息，你的网游编年史排名在XX名哟，快去看看吧
		// UserInfo loginUserInfo = userInfoService.getUserInfoByPassport();
		// model.addAttribute("loginUserInfo", loginUserInfo);
		UserInfo userinfo = userInfoService.getUserInfoByUserId(WebUtil.returnUserId(request, response));
		if (userinfo != null) {
			Integer rank = userInfoService.calculateRank(userinfo.getUserId());
			model.addAttribute("userinfo", userinfo);
			model.addAttribute("rank", rank);
		}
		
		//判断是否打开了他的编年史页面
		UserInfo hisGameHistoryCloseFlag = (UserInfo) session.getAttribute("hisGameHistoryCloseFlag");
		if (hisGameHistoryCloseFlag != null) {
			model.addAttribute("hisSpace", hisGameHistoryCloseFlag);
		}
		
		model.addAttribute("userCount", userInfoService.userCount());

		logger.debug("gamehistory index...");
		return "front/index";
	}
	
	/**
	 * 模拟登录，假登录
	 */
	@RequestMapping(value = { "loginMock" })
	public String loginMock(Model model, HttpSession session, Integer userId, 
			HttpServletRequest request, HttpServletResponse response) {

		if (userId == null || userId == 0) {
			return "front/login";
		}
		
		UserInfo userinfo = userInfoService.getUserInfoByUserId(userId);
		if (userinfo == null) {
			return "front/login";
		}
		session.setAttribute(ApplicationConstants.FRONT_SESSION_USER, userinfo);
		return "redirect:/f/index";
	}
	
	/**
	 * <p>Ajax校验登录.</p>
	 * 
	 * 检查SohuPassport：
	 *     如果已登录，则将登录信息注入Session；
	 *     如果没有登录，返回状态给客户端，客户端会弹出登陆框
	 * @throws IOException 
	 * @throws ServletException 
	 */
	@RequestMapping(value = { "login" })
	public String login(Model model, HttpSession session, String url,
			HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// TODO 需要调整此处代码
		Integer uid = WebUtil.returnUserId(request, response);
		logger.info("uid==========  "+uid );
		if (uid.equals(0)) {
			// 未登录
			logger.info("获取uid值为0，返回首页登录  " );
			model.addAttribute("needLogin", "true");
			return this.index(model, session,request,response);
		} else {
			UserInfo userinfo = userInfoService.getUserInfoByUserId(uid);
			if (userinfo == null) {
				try{
					userinfo=new UserInfo();
					userinfo.setCreateTime(DateUtility.now());
					userinfo.setHonor("潜力级");
					logger.info("调用 getMemberInfo begin " );
					String jsonString=AnnalsClient.getMemberInfo(uid);
					logger.info("调用 getMemberInfo end jsonString=== "+ jsonString);
					MemberInfo memberinfo=jsonMapper.fromJson(jsonString, MemberInfo.class);
					Account account=memberinfo.getAccount();
					if(account!=null){
						logger.info("passport==="+ account.getAccId());
						userinfo.setNickname(account.getNickname());
						userinfo.setPassport(account.getAccId());
						userinfo.setSmallImage(WebUtil.staticGetHeadshot(account.getAccId()));
					}
					userinfo.setCostCount(0d);
					userinfo.setGameCount(0);
					userinfo.setGameBeginTime(0);
					userinfo.setGameLastestTime(2012);
					userinfo.setStoryCount(0);
					userinfo.setUpdateCount(0);
					userinfo.setUserId(uid);
					userInfoService.saveUserInfo(userinfo);
					
				}catch(Exception e){
					logger.error("保存新用户失败  ", e);
					throw ExceptionUtility.unchecked(e);
				}
				
			}
		}
		logger.info("indexController    aaaaaa");
		request.getRequestDispatcher("/f/space").forward(request, response);
		return null;
	}


}
